'use client';

import { Button } from '@/components/ui/Button';
import {
  DropdownMenu,
  DropdownMenuContent,
  DropdownMenuItem,
  DropdownMenuTrigger,
} from '@/components/ui/DropdownMenu';
import { trpcPureClient } from '@/utils/api';
import { useQuery } from '@tanstack/react-query';
import Link from 'next/link';
import { use } from 'react';

export default function AppDashboardNav({
  params,
}: {
  params: Promise<{
    id: string;
  }>;
}) {
  const { id } = use(params);
  const { data: apps, isPending } = useQuery({
    queryKey: ['apps'],
    queryFn: async () => {
      return trpcPureClient.apps.listApps.query();
    },
  });

  const currentApp = apps?.find((app) => app.id === id);

  return (
    <DropdownMenu>
      <DropdownMenuTrigger asChild>
        <Button variant="ghost">
          {isPending ? 'Loading' : currentApp ? currentApp.name : '...'}
        </Button>
      </DropdownMenuTrigger>
      <DropdownMenuContent>
        {apps?.map((app) => {
          return (
            <DropdownMenuItem
              key={app.id}
              disabled={currentApp?.id === app.id}
              asChild
            >
              <Link href={`/dashboard/apps/${app.id}`}>{app.name}</Link>
            </DropdownMenuItem>
          );
        })}
      </DropdownMenuContent>
    </DropdownMenu>
  );
}
